package com.security.securityAutoConfiguration;

import com.common.util.StringUtil;
import com.security.authority.metadata.RpcSecurityMetadataSource;
import com.security.config.SecurityConfig;
import com.security.filter.TokenAuthFilter;
import com.security.service.AuthenticateService;
import com.security.service.AuthenticateUrlManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

import static com.security.authority.metadata.AbstractSecurityMetadataSource.SECURITY_METADATA_SOURCE_BEAN_NAME;
import static com.security.filter.AbstractTokenAuthenticationFilter.TOKEN_AUTH_FILTER_BEAN_NAME;

/**
 * 默认提供的springSecurity自动配置--需要配置security.default.open=true来开启
 * @author 大忽悠
 * @create 2022/10/11 19:31
 */
@Configuration
@AutoConfigureBefore(AuthenticateService.class)
@ConditionalOnProperty(prefix = "security", name = "defaultAutoConfig", havingValue = "true")
@EnableConfigurationProperties(SecurityConfig.class)
@Slf4j
public class DefaultSecurityAutoConfiguration {

    @Resource
    private SecurityConfig securityConfig;

    @Bean
    @ConditionalOnMissingBean
    public AuthenticateService authenticateService(AuthenticateUrlManager authenticateUrlManager)
    {
        return new AuthenticateService(authenticateUrlManager);
    }

    @Bean
    @ConditionalOnMissingBean
    public AuthenticateUrlManager authenticateUrlManager()
    {
        String authenticateCenterUrl = securityConfig.getAuthenticateCenterUrl();
        if(StringUtil.isNullOrEmpty(authenticateCenterUrl)){
            throw new RuntimeException("security.authenticateCenterUrl属性未配置或者配置的属性为空");
        }
        return new AuthenticateUrlManager(authenticateCenterUrl);
    }

    @Bean(TOKEN_AUTH_FILTER_BEAN_NAME)
    @ConditionalOnMissingBean
    public TokenAuthFilter tokenAuthFilter(AuthenticateService authenticateService){
        log.info("注入了默认配置的tokenAuthFilter");
        return new TokenAuthFilter(authenticateService);
    }

    @Bean(SECURITY_METADATA_SOURCE_BEAN_NAME)
    @ConditionalOnMissingBean
    public RpcSecurityMetadataSource rpcSecurityMetadataSource(AuthenticateService authenticateService){
        log.info("注入了默认配置的RpcSecurityMetadataSource");
        return new RpcSecurityMetadataSource(authenticateService);
    }
}
